'use strict';


/************custom const****************/
const UNIX_SOCKET = '/var/run/docker.sock';
const API_PATH_CONTAINERS_JSON = 'GET /containers/json HTTP/1.1\r\n\r\n';
const LOG_PATH = '/var/lib/docker/containers/{containerId}/{containerId}-json.log';
/************custom const****************/

const net = require('net');
const logger = console.log.bind(console);


const SOCK_STATUS = {
    UNDEFINED: 'undefined', //0,
    NOT_CONNECT: 'not_connect', //1,
    CONNECTED: 'connected', //2,
    DISCONNECTED: 'disconnected', //3,
    CLOSE: 'close', // 4,
}

class DockerApi {
    constructor() {
        let self = this;

        self.preStatus = SOCK_STATUS.UNDEFINED;
        self.status = SOCK_STATUS.NOT_CONNECT;
        self.responseList = [];

        self._socketClient = net.createConnection(UNIX_SOCKET);
        self._socketClient.on('connect', function() {
            self._statusChangeTo(SOCK_STATUS.CONNECTED);
        });

        self._socketClient.on('data', function(chunk) {
            // logger('get data\n', chunk.toString());
            self.responseList.push(chunk);
        });
    }

    _waitResponse() {
        var self = this;
        return new Promise(function(fulfil, reject) {
            var it = setInterval(function() {
                if (self.responseList.length != 0) {
                    var data = self.responseList.shift();
                    clearInterval(it);
                    fulfil(data);
                }
            }, 1000);
        });
    }

    _prepare() {
        var self = this;
        return new Promise(function(fulfil, reject) {
            var it = setInterval(function() {
                if (self.status == SOCK_STATUS.CONNECTED) {
                    clearInterval(it);
                    fulfil();
                } else {
                    logger('wait connected');
                }
            }, 1000);
        });
    }

    // just log
    _statusChangeTo(newStatus) {
        let self = this;
        self.preStatus = self.status;
        self.status = newStatus;
        logger('status change:' + self.preStatus + ' -> ' + self.status);
    }


    // return promise
    getContainers() {
        logger("getContainer");
        let self = this;

        return self._prepare()
            .then(function() {
                logger('send data');
                self._socketClient.write(API_PATH_CONTAINERS_JSON);
                return self._waitResponse();
            });
    }

    getContainerId(data) {
        logger("getContainerId");
        let bodyIndex = data.indexOf('\r\n\r\n');
        // logger(bodyIndex);
        let body = data.toString().substring(bodyIndex + 4, data.length);
        body = JSON.parse(body);
        //logger("body type=",typeof body);
        //logger("body=\n",body);
        let id = body[0].Id;
        return id;
    }

    getLogfile(containerId) {
        logger("getLogfile");
        return LOG_PATH.replace(/{containerId}/g, containerId);
    }
}


module.exports = DockerApi;